package respository

import (
	"gorm.io/gorm"
	"uniquen.top/golang-demo/common"
	"uniquen.top/golang-demo/model"
)

type CategoryRepository struct {
	DB *gorm.DB
}

func NewCategoryRepository() CategoryRepository {
	return CategoryRepository{DB: common.DB}
}

func (c CategoryRepository) Create(name string) (*model.Category, error) {

	category := model.Category{
		Name: name,
	}

	if err := c.DB.Create(&category).Error; err != nil {
		return nil, err
	}

	return &category, nil
}

func (c CategoryRepository) Update(name string, category model.Category) (*model.Category, error) {
	// 更新分类(更新单个类: https://gorm.io/zh_CN/docs/update.html)
	if err := c.DB.Model(&category).Update("name", name).Error; err != nil {
		return nil, err
	}

	return &category, nil
}

func (c CategoryRepository) Query(id int) (*model.Category, error) {
	var category model.Category
	if err := c.DB.First(&category, id).Error; err != nil {
		return nil, err
	}

	return &category, nil
}

func (c CategoryRepository) Delete(id int) error {
	if err := c.DB.Delete(&model.Category{}, id).Error; err != nil {
		return err
	}

	return nil
}
